package schoolword;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;

class Bank {
    public static double money = 0;  //一开始的钱为0

    //存钱
    public synchronized void addMoney(double m) throws InterruptedException {
        Thread.sleep(2000);
        money = money + m;
        System.out.println("存入的金额为: " + m + ",当前余额是: " + String.format("%.1f",money));
        this.notify();
    }

    //取钱
    public synchronized  void subMoney(double n) throws InterruptedException {
        if (money <= n) {
            System.out.println ( "取款金额是: "+ n +"当前余额是: " + String.format("%.1f",money) + ",余额不足");
            this.wait();   //等别人存钱
            //没钱了
        }else {
            Thread.sleep(2000);
            money = money - n;
            System.out.println("取款金额是: " + n + "当前余额是: " + String.format("%.1f",money));
        }

    }
}

class Consumer implements Runnable {
    private Bank bank;

    public Consumer (Bank bank) {
        this.bank = bank;
    }
    @Override
    public void run() {
        while (true) {
            Random random = new Random();
           // Bank bank = new Bank();
         double val =   (random.nextDouble() * 100) ;
            DecimalFormat  df = new DecimalFormat("#.#");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String str = df.format(val);
            double val1 = Double.parseDouble(str);
            try {
                bank.subMoney(val1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }
}

class Producer implements Runnable{
    private Bank bank;

    public Producer(Bank bank) {
        this.bank = bank;
    }
    @Override
    public void run() {
        while (true) {
            Random random = new Random();
          //  Bank bank = new Bank();
         double val =   (random.nextDouble() *100);
            DecimalFormat  df = new DecimalFormat("#.#");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String str = df.format(val);
            double val2 = Double.parseDouble(str);
            try {
                bank.addMoney(val2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Bank bank = new Bank();
        Thread thread1 = new Thread(new Consumer(bank));
        Thread thread = new Thread(new Producer(bank));
        thread.start();
        thread1.start();
    }
}
